<template>
  <el-card class="search-card">
    <el-form :inline="true" class="search-form">
      <el-form-item label="表名称">
        <el-input
            @keyup.enter="search"
            placeholder="请输入表名称"
            v-model="pageRequest.model.tableName"
            clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="表描述">
        <el-input
            @keyup.enter="search"
            placeholder="请输入表描述"
            v-model="pageRequest.model.tableComment"
            clearable>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">搜索</el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card class="table-card">
    <el-button icon="ChatLineSquare" type="danger" plain size="default" @click="showDialog = true">使用说明</el-button>
    <el-button icon="Connection" type="warning" plain size="default" @click="dataBaseConfig">数据库配置</el-button>
    <el-button icon="Operation" type="primary" plain size="default" @click="generateConfig">系统配置</el-button>
    <el-button icon="Download" type="info" plain size="default" :disabled="tableNames.length === 0" @click="generateSelect">代码生成</el-button>
    <el-table @selection-change="select" border class="table" :data="items">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column type="index" width="100px" label="序号" align="center" :index="(index) => index + 1"></el-table-column>
      <el-table-column label="表名称" align="center" prop="tableName" show-overflow-tooltip></el-table-column>
      <el-table-column label="表描述" align="center" prop="tableComment" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" prop="creatTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #="{ row }">
          <el-button type="primary" size="small" icon="Edit" @click="generate(row)">代码生成</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="pageRequest.page.index"
        v-model:page-size="pageRequest.page.size"
        :page-sizes="[10, 20, 30, 50]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findPage"
        @size-change="findPage"/>
  </el-card>
  <el-drawer v-model="dialog">
    <template #header>
      <h4>{{ generalConfig.type==="DataBase" ? '数据库配置' : '代码生成器配置' }}</h4>
    </template>
    <template #default>
      <el-form v-if="generalConfig.type==='DataBase'" :model="dataSource" :rules="rules" ref="form" label-position="right" label-width="120px">
        <el-form-item class="form-item" label="数据库驱动" prop="driver">
          <el-input placeholder="请输入数据库驱动" v-model="dataSource.driver"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="数据库地址" prop="url">
          <el-input placeholder="请输入数据库地址" v-model="dataSource.url"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="数据库账号" prop="username">
          <el-input placeholder="请输入数据库账号" v-model="dataSource.username"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="数据库密码" prop="password">
          <el-input placeholder="请输入数据库密码" v-model="dataSource.password"></el-input>
        </el-form-item>
      </el-form>
      <el-form v-else :model="codeGenerate" ref="form" label-position="right" label-width="120px">
        <el-form-item class="form-item" label="作者名称" prop="currentUser">
          <template #label>
                        <span>
                           <el-tooltip content="如果不输入，默认使用系统名称"
                                       placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           作者名称
                        </span>
          </template>
          <el-input placeholder="请输入作者名称" v-model="codeGenerate.currentUser"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="表名去除部分" prop="tableExclusion">
          <template #label>
                        <span>
                           <el-tooltip content="不用加 _ "
                                       placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           表名去除部分
                        </span>
          </template>
          <el-input placeholder="请输入表名去除部分" v-model="codeGenerate.tableExclusion"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="接口前缀" prop="pathPrefix">
          <el-input placeholder="请输入接口前缀" v-model="codeGenerate.pathPrefix"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="注释名称" prop="comment">
          <el-input placeholder="请输入注释名称" v-model="codeGenerate.comment"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="dialog = false">关闭页面</el-button>
        <el-button v-if="generalConfig.type==='DataBase'" type="danger" @click="testConnect">测试连接</el-button>
        <el-button type="primary" @click="save">保存配置</el-button>
      </div>
    </template>
  </el-drawer>

  <el-dialog
      title="代码生成器使用说明"
      v-model="showDialog"
      width="820px"
      :header-style="{ fontSize: '18px', borderBottom: '1px solid #eee' }"
      class="instruction-dialog"
  >
    <!-- 添加标题栏图标 -->
    <template #header>
      <div class="dialog-header">
        <el-icon :size="22" color="#409EFF" class="title-icon"><info-filled /></el-icon>
        <span class="dialog-title">代码生成器使用说明</span>
        <el-tag type="info" size="small" class="version-tag">v2.0</el-tag>
      </div>
    </template>

    <!-- 添加简介说明 -->
    <div class="intro-section">
      <el-alert
          title="欢迎使用代码生成器"
          description="本工具可以帮助您快速生成标准的CRUD代码，提升开发效率。请按照以下步骤操作："
          type="info"
          :closable="false"
          show-icon
          class="intro-alert">
      </el-alert>
    </div>

    <!-- 优化后的说明列表 -->
    <div class="enhanced-instruction-list">
      <div
          v-for="(item, index) in instructions"
          :key="index"
          :class="['instruction-card', `card-${item.type}`]"
      >
        <div class="card-header">
          <div :class="['step-badge', `badge-${item.type}`]">
            <el-icon :size="16"><component :is="item.icon" /></el-icon>
            <span class="step-number">{{ index + 1 }}</span>
          </div>
          <h3 class="card-title">{{ item.title }}</h3>
          <el-tag :type="item.type" size="small" class="type-tag">{{ getTypeLabel(item.type) }}</el-tag>
        </div>
        <div class="card-content">
          <p class="description">{{ item.content }}</p>
        </div>
        <div class="card-footer">
          <el-progress :percentage="((index + 1) / instructions.length) * 100" :show-text="false" :stroke-width="3" class="progress-bar"></el-progress>
        </div>
      </div>
    </div>

    <!-- 添加底部提示 -->
    <div class="footer-tips">
      <el-divider content-position="center">
        <el-icon color="#409EFF"><StarFilled /></el-icon>
        <span style="margin: 0 8px; color: #666;">温馨提示</span>
        <el-icon color="#409EFF"><StarFilled /></el-icon>
      </el-divider>
      <p class="tip-text">
        如遇到问题，请检查数据库连接是否正常，确保表结构符合规范。更多帮助请查阅开发文档。
      </p>
    </div>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted, reactive, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import {
  InfoFilled,
  Connection,
  Operation,
  Select,
  Download,
  FolderAdd,
  Menu,
  Upload,
  CircleCheck,
  StarFilled,
  ArrowRight,
  QuestionFilled
} from '@element-plus/icons-vue'
import setting from "@/setting.js"
import {getConfig, setConfig} from "@/api/system/config/index.js";
import {testConnection, findPageApi, generateCode} from "@/api/tool/generate/index.js";

const showDialog = ref(false);

// 分页参数
const pageRequest = ref({
  page: {index: 1, size: 10},
  model: {
    tableName: '',
    tableComment: '',
  }
})

const instructions = ref([
  {
    title: '配置数据库连接',
    content: '点击"数据库配置"按钮，填写数据库驱动、地址、账号和密码信息。建议先点击"测试连接"确保配置正确。',
    icon: 'Connection',
    type: 'warning'
  },
  {
    title: '设置生成参数',
    content: '点击"系统配置"按钮，配置作者名称、表名去除部分、接口前缀等参数。这些参数将影响生成代码的格式和内容。',
    icon: 'Operation', 
    type: 'primary'
  },
  {
    title: '选择数据表',
    content: '在表格中勾选需要生成代码的数据表。支持按表名称和表描述进行筛选搜索，也可以批量选择多个表进行操作。',
    icon: 'Select',
    type: 'success'
  },
  {
    title: '生成代码文件',
    content: '选择表后点击"代码生成"按钮，系统将自动生成对应的Java实体类、Mapper、Service、Controller等文件，并打包下载。',
    icon: 'Download',
    type: 'info'
  },
  {
    title: '创建项目模块',
    content: '在项目中新建一个Module，在open-sys的pom.xml中引入依赖，在open-server的pom.xml中也添加相同依赖。',
    icon: 'FolderAdd',
    type: 'primary'
  },
  {
    title: '配置系统菜单',
    content: '在菜单管理中新建目录和菜单项，组件路径设置为views目录下对应的页面路径，配置相应的权限标识。',
    icon: 'Menu',
    type: 'success'
  },
  {
    title: '添加代码文件',
    content: '将生成的代码文件放置到项目对应目录中：实体类放入entity包，Mapper放入mapper包，Service放入service包等。',
    icon: 'Upload',
    type: 'warning'
  },
  {
    title: '测试功能模块',
    content: '启动项目，访问新建的菜单页面，测试增删改查等基础功能是否正常工作，如有问题及时调整代码。',
    icon: 'CircleCheck',
    type: 'success'
  }
]);

// 配置信息
let generalConfig = reactive({
  //配置类型
  type: '',
  // 配置信息
  config: ref({})
})

// 数据库信息
let dataSource = reactive({
  driver: '',
  url: '',
  username: '',
  password: '',
})

// 配置信息
let codeGenerate = reactive({
  currentUser: '',
  tableExclusion: '',
  pathPrefix: '',
  comment: '',
})

// 基础数据
const items = ref([])
const tableNames = ref([])
const total = ref(0)
const dialog = ref(false)
const form = ref()

// 分页查询接口
const findPage = async (index = 1) => {
  const result = await findPageApi(pageRequest.value)
  if (result.code === setting.SYSTEM_SUCCESS) {
    total.value = result.data.total
    items.value = result.data.items
  }
}

// 表格选择事件
const select = (value) => {
  // 只保存选中行的 tableName 字段
  tableNames.value = value.map(item => item.tableName)
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  const typeMap = {
    'warning': '配置',
    'primary': '设置',
    'success': '操作',
    'info': '生成'
  }
  return typeMap[type] || '步骤'
}


// 搜索
const search = () => findPage()
// 重置
const reset = () => {
  pageRequest.value = {
    page: {index: 1, size: 10},
    model: {
      tableName: '',
      tableComment: '',
    }
  };
  findPage();
}

// 数据库配置信息
const dataBaseConfig = () => {
  generalConfig.type = 'DataBase'
  getConfig(generalConfig).then(res => {
    if (res.code === setting.SYSTEM_SUCCESS){
      dialog.value = true
      Object.assign(dataSource, res.data);
    }
  })
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('driver');
    form.value.clearValidate('url');
    form.value.clearValidate('username');
    form.value.clearValidate('password');
  })
}

// 代码生成器配置
const generateConfig = () => {
  generalConfig.type = 'Generate'
  getConfig(generalConfig).then(res => {
    if (res.code === setting.SYSTEM_SUCCESS){
      dialog.value = true
      Object.assign(codeGenerate, res.data);
    }
  })
}

const generateSelect = async () => {
  await generateCode(tableNames.value).then(response => {
    // 创建一个blob对象
    const blob = new Blob([response.data], {type: response.headers['Content-Type']});
    // 创建一个a标签
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // 设置下载文件的文件名
    link.download = decodeURIComponent(response.headers['content-disposition'].split('filename=')[1].replace(/"/g, ''));
    // 触发点击事件下载文件
    link.click();
    ElMessage({type: 'success', message: '下载成功'});
  }).catch((reason) => {
    ElMessage({type: 'error', message: '下载失败'});
  })
}

// 生成代码
const generate = async (row) => {
  tableNames.value = [row.tableName] // 清空原有内容，只保留当前表名
  await generateCode(tableNames.value).then(response => {
    // 创建一个blob对象
    const blob = new Blob([response.data], {type: response.headers['Content-Type']});
    // 创建一个a标签
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // 设置下载文件的文件名
    link.download = decodeURIComponent(response.headers['content-disposition'].split('filename=')[1].replace(/"/g, ''));
    // 触发点击事件下载文件
    link.click();
    ElMessage({type: 'success', message: '下载成功'});
  }).catch((reason) => {
    ElMessage({type: 'error', message: '下载失败'});
  })
}

// 保存配置
const save = async () => {
  await form.value.validate(valid => {
    if (valid) {
      generalConfig.type === 'DataBase' ? generalConfig.config = dataSource
          : generalConfig.config = codeGenerate
      setConfig(generalConfig).then(res => {
        if (res.code === setting.SYSTEM_SUCCESS) {
          ElMessage.success('保存成功')
          dialog.value = false
          findPage();
        }
      })
    }
  });

}

// 测试连接
const testConnect = async () => {
  await form.value.validate(valid => {
    if (valid) {
      testConnection(dataSource).then(res => {
        if (res.code === setting.SYSTEM_SUCCESS) {
          ElMessage.success('数据库连接成功')
        }
      })
    }
  });
}

// 验证规则（在script setup中添加）
const rules = reactive({
  driver: [
    { required: true, message: '数据库驱动不能为空', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '数据库地址不能为空', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '数据库账号不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '数据库密码不能为空', trigger: 'blur' },
  ]
});

onMounted(() => {
  findPage()
})
</script>

<style scoped>
.search-card {
  min-height: 80px;

  .search-form {
    margin-top: 15px;
  }
}

.table-card {
  margin: 10px 0;

  .table {
    margin: 10px 0;

    .form-item {
      width: 300px;
    }
  }
}

.drawer-footer {
  flex: auto;
}

.dialog-header {
  display: flex;
  align-items: center;
  padding: 12px 0;
}

/* Dialog header styling */
.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-left: 8px;
  flex: 1;
}

.version-tag {
  margin-left: auto;
}

.title-icon {
  margin-right: 8px;
}

/* Intro section styling */
.intro-section {
  margin-bottom: 20px;
}

.intro-alert {
  border-radius: 8px;
  border: 1px solid #e6f4ff;
}

/* Enhanced instruction list styling */
.enhanced-instruction-list {
  padding: 0;
  margin: 0;
}

.instruction-card {
  background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f0f0f0;
  position: relative;
}

.instruction-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.instruction-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, var(--card-color), var(--card-color-light));
}

/* Different color themes for each card type */
.card-warning {
  --card-color: #f56c6c;
  --card-color-light: #fef0f0;
}

.card-primary {
  --card-color: #409eff;
  --card-color-light: #ecf5ff;
}

.card-success {
  --card-color: #67c23a;
  --card-color-light: #f0f9ff;
}

.card-info {
  --card-color: #909399;
  --card-color-light: #f4f4f5;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 16px 20px 12px;
  border-bottom: 1px solid #f5f5f5;
}

.step-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--card-color);
  color: white;
  font-size: 12px;
  font-weight: 600;
  padding: 6px 12px;
  border-radius: 20px;
  margin-right: 12px;
  min-width: 60px;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.step-number {
  font-weight: 700;
}

.card-title {
  flex: 1;
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.type-tag {
  margin-left: auto;
  font-weight: 500;
}

.card-content {
  padding: 16px 20px;
}

.card-content .description {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  text-align: justify;
}

.card-footer {
  padding: 12px 20px 16px;
}

.progress-bar {
  margin-top: 8px;
}

/* Footer tips styling */
.footer-tips {
  margin-top: 24px;
  padding: 16px;
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
  border-radius: 8px;
  border: 1px solid #e6f4ff;
}

.tip-text {
  margin: 8px 0 0;
  font-size: 13px;
  color: #666;
  text-align: center;
  line-height: 1.5;
}

/* Animation removed to prevent shake effect */

/* Responsive adjustments */
@media (max-width: 768px) {
  .dialog-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .version-tag {
    margin-left: 0;
    align-self: flex-end;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .step-badge {
    margin-right: 0;
    align-self: flex-start;
  }

  .type-tag {
    margin-left: 0;
    align-self: flex-end;
  }

  .card-content .description {
    font-size: 13px;
  }
}

/* Custom dialog styling */
.instruction-dialog .el-dialog__body {
  padding: 16px 20px 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.instruction-dialog .el-dialog__header {
  padding: 16px 20px 12px;
}

/* Custom scrollbar for dialog content */
.instruction-dialog .el-dialog__body::-webkit-scrollbar {
  width: 6px;
}

.instruction-dialog .el-dialog__body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.instruction-dialog .el-dialog__body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.instruction-dialog .el-dialog__body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

</style>